<!--
 * @Author: Liz.Zheng
 * @Date: 2021-10-27 13:44:24
 * @LastEditTime: 2022-12-07 14:19:15
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 编辑、增加流水账号
 * @Motto: Write the code. Change the world.
-->

<template>
  <a-drawer
    :title="title"
    :visible="visible"
    :destroyOnClose="true"
    :width="$store.getters.isMobile ? 350 : 450"
    :body-style="{ paddingBottom: '80px' }"
    @close="closeModal"
  >
    <a-form layout="vertical">
      <a-form-item label="分类名称" v-bind="validateInfos.name">
        <a-input placeholder="请输入分类名称" v-model:value="modelRef.name" />
      </a-form-item>
      <a-form-item label="分类描述" v-bind="validateInfos.desc">
        <a-input placeholder="请输入分类描述" v-model:value="modelRef.desc" />
      </a-form-item>
      <a-form-item label="分类样式">
        <template v-for="(item, index) in tagColorData" :key="index">
          <div
            class="labelItem"
            :style="{
              borderColor: 'rgb(' + item.borderColor + ')',
              backgroundColor: 'rgb(' + item.bgColor + ')',
            }"
            @click="changeTagColor(index)"
          >
            <CheckOutlined v-if="index == modelRef.colorIndex" />
          </div>
        </template>
      </a-form-item>
      <a-form-item label="状态" v-bind="validateInfos.status">
        <a-switch
          :checkedValue="1"
          :unCheckedValue="0"
          v-model:checked="modelRef.status"
          checked-children="开启"
          un-checked-children="关闭"
        />
      </a-form-item>
      <a-form-item v-bind="validateInfos.user_show">
        <template #label>
          <span style="padding-right: 5px">用户是否可见</span>
          <a-tooltip>
            <template #title>若关闭仅在管理后台展示</template>
            <QuestionCircleOutlined />
          </a-tooltip>
        </template>

        <a-switch
          :checkedValue="1"
          :unCheckedValue="0"
          v-model:checked="modelRef.user_show"
          checked-children="开启"
          un-checked-children="关闭"
        />
      </a-form-item>
    </a-form>
    <div class="drawer-footer">
      <a-button class="mr-10" @click.prevent="closeModal">取消</a-button>
      <a-button type="primary" @click.prevent="onSubmit">保存</a-button>
    </div>
  </a-drawer>
</template>

<script>
import { computed, defineComponent, reactive, ref, toRaw, watch } from "vue";
import { Form, message } from "ant-design-vue";
import request from "@/common/utils/request";
import { CheckOutlined, QuestionCircleOutlined } from "@ant-design/icons-vue";
const useForm = Form.useForm;
import BLCOMMON from "bl-common-vue3";

export default defineComponent({
  name: "EditTag",
  components: {
    CheckOutlined,
    QuestionCircleOutlined,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: 0,
    },
  },
  setup(props, context) {
    /**
     * @description: 标题显示
     */
    const title = computed(() => {
      return "新增" + BLCOMMON.utils.L("房源") + "标签";
    });

    /**
     * @description: 触发关闭
     */
    const closeModal = () => {
      context.emit("closeTag");
    };

    /**
     * @description: 表单字段
     */
    const modelRef = reactive({
      name: "",
      desc: "",
      colorIndex: 0,
      status: 1,
      user_show: 1,
    });

    // 切换标签
    const changeTagColor = (index) => {
      modelRef.colorIndex = index;
    };

    //获取标签样式
    const tagColorData = ref([]);

    const getTagColorData = () => {
      request.get("/org", "/manage/taglib/industry/color").then((res) => {
        tagColorData.value = res.list || [];
      });
    };

    /**
     * @description: 验证规则
     */
    const rulesRef = reactive({
      name: [{ required: true, message: "标签名称为必填项" }],
      status: [{ required: true }],
      user_show: [{ required: true }],
    });

    /**
     * @description: 创建表单
     */
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    /**
     * @description: 提交表单
     */
    const onSubmit = () => {
      validate()
        .then(() => {
          let params = { ...toRaw(modelRef), needMsg: true };
          params.color = tagColorData.value[modelRef.colorIndex];
          console.log(params);
          console.log(tagColorData.value);
          const success = (res) => {
            message.success(res.msg || "保存成功");
            context.emit("success");
          };
          if (props.id) {
            params.id = props.id;
            request.put("/org", "/manage/taglib/house", params).then((res) =>
              success(res)
            );
          } else {
            request.post("/org", "/manage/taglib/house", params).then((res) =>
              success(res)
            );
          }
        })
        .catch((err) => {
          console.log("error", err);
        });
    };

    /**
     * @description: 获取编辑信息
     */
    const getEditInfo = () => {
      request.get("/org", "/manage/taglib/industry/get", { id: props.id }).then(
        (res) => {
          const { detail } = res;
          setModelRef({
            name: detail.name,
            desc: detail.desc,
            colorIndex: detail.colorIndex,
            status: detail.status,
          });
        }
      );
    };

    const setModelRef = (state) => {
      for (let key in state) {
        modelRef[key] = state[key];
      }
    };

    /**
     * @description: 初始化
     */
    const init = () => {
      getTagColorData();
      if (props.id) {
        getEditInfo();
      }
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          // 打开时初始化数据
          init();
        } else {
          // 关闭时重置数据
          resetFields();
        }
      }
    );
    return {
      title,
      closeModal,
      validateInfos,
      changeTagColor,
      tagColorData,
      resetFields,
      modelRef,
      onSubmit,
    };
  },
});
</script>

<style>
.labelItem {
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  display: inline-block;
  margin-right: 16px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 20px;
  opacity: 1;
  cursor: pointer;
  position: relative;
}
.labelItem .anticon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
